<script setup>
import { Edit, Delete } from "@element-plus/icons-vue";

import { ref } from "vue";

//文章分类数据模型
const categorys = ref([
  {
    id: "",
    name: "",
  },
]);
const bookname = ref("");
const author = ref("");
const bookId = ref("");

//用户搜索时选中的分类id
const categoryId = ref("");

//用户搜索时选中的发布状态
const state = ref("");

//文章列表数据模型
const book = ref([
  {
    id: 5,
    bookname: "书名",
    type: 2,
    author: "作者",
    num: 3,
    address: "地点",
    idNumber: "bianhao",
  },
]);

//分页条数据模型
const pageNum = ref(1); //当前页
const total = ref(20); //总条数
const pageSize = ref(10); //每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size;
  bookList();
};
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num;
  bookList();
};

import {
  bookClassifyListService,
  bookClassifyByNameService,
  bookListService,
  addBookService,
  updateBookService,
  bookDeleteService,
} from "@/api/books.js";

//回显文章分类
const bookClassifyList = async () => {
  let result = await bookClassifyListService();
  categorys.value = result.data;
};

//获取图书列表数据
const bookList = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    bookname: bookname.value ? bookname.value : null,
    categoryId: categoryId.value ? categoryId.value : null,
    author: author.value ? author.value : null,
    bookId: bookId.value ? bookId.value : null,
  };
  let result = await bookListService(params);

  //渲染视图
  total.value = result.data.total;
  book.value = result.data.items;

  //处理数据，给数据模型扩展一个属性categoryName，分类名称
  for (let i = 0; i < book.value.length; i++) {
    let book1 = book.value[i];
    for (let j = 0; j < categorys.value.length; j++) {
      if (book1.type == categorys.value[j].id) {
        book1.categoryName = categorys.value[j].name;
      }
    }
  }
};

bookClassifyList();
bookList();

import { Plus } from "@element-plus/icons-vue";
//控制抽屉是否显示
const visibleDrawer = ref(false);
//定义变量，控制标题的展示
const title = ref("");

//添加表单数据模型
const bookModel = ref({
  id: "",
  bookname: "",
  type: "",
  author: "",
  num: "",
  address: "",
  idNumber: "",
});
const is = ref(true)
//自定义校验函数
const reDisable = (rule, value, callback) => {
    if (value == null || value === '') {
      is.value=true
        // callback()
    }else if (bookModel.value.bookname == null|| bookModel.value.bookname === ''||bookModel.value.idNumber == null|| bookModel.value.idNumber === '') {
      is.value=true
    }else{
        is.value=false
        callback()
    }
}
//添加图书表单校验
const rules = {
  bookname: [
    { required: true, message: "请输入图书名称", trigger: "blur" },
    { min: 1, max: 20, message: "长度不超过20位非空字符", trigger: "blur" },
    { validator: reDisable, trigger: 'change' }
  ],
  idNumber: [
    { required: true, message: "请输入图书编号", trigger: "blur" },
    { min: 1, max: 10, message: "长度不超过10位非空字符", trigger: "blur" },
    { validator: reDisable, trigger: 'change' }
  ],
};

//清空模型的数据
const clearDate = () => {
  //   bookModel.value = "";
  bookModel.value.bookname = "";
  bookModel.value.type = "";
  bookModel.value.author = "";
  bookModel.value.num = "1";
  bookModel.value.address = "";
  bookModel.value.idNumber = "";
};

//调用接口，添加表单
import { ElMessage, ElMessageBox } from "element-plus";
const addBook = async () => {
  //调用接口
  let result = await addBookService(bookModel.value);
  ElMessage.success(result.msg ? result.msg : "添加成功");

  //调用获取所有图书的函数
  bookList();

  visibleDrawer.value = false;
};

//展示编辑弹窗
const showDrawer = (row) => {
  visibleDrawer.value = true;
  title.value = "修改图书";
  //数据拷贝
  bookModel.value.bookname = row.bookname;
  bookModel.value.type = row.type;
  bookModel.value.author = row.author;
  bookModel.value.num = row.num;
  bookModel.value.address = row.address;
  bookModel.value.idNumber = row.idNumber;
  //扩展id属性，将来需要传递给后台
  bookModel.value.id = row.id;
};

//修改图书
const updateBook = async () => {
  //调用接口

  let result = await updateBookService(bookModel.value);

  ElMessage.success(result.msg ? result.msg : "修改成功");

  //调用获取所有图书的函数
  bookList();

  //隐藏弹窗
  visibleDrawer.value = false;
};

//删除图书
const deleteBook = (row) => {
  //提示用户 确认框

  ElMessageBox.confirm("是否确认删除该分类?", "温馨提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      //调用接口
      let result = await bookDeleteService(row.id);

      ElMessage({
        type: "success",
        message: "删除成功",
      });

      //刷新列表
      bookList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};
</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>图书管理</span>
        <div class="extra">
          <el-button
            type="primary"
            @click="
              visibleDrawer = true;
              title = '添加图书';
              clearDate();
            "
            >添加图书</el-button
          >
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->

    <el-form inline>
      <!-- <el-input v-model="input" placeholder="Please input" clearable /> -->
      <el-form-item>
        <el-input v-model="bookname" placeholder="请输入书名" clearable />
      </el-form-item>
      <el-form-item label="图书分类：">
        <el-select placeholder="请选择" v-model="categoryId">
          <el-option
            v-for="c in categorys"
            :key="c.id"
            :label="c.name"
            :value="c.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-input v-model="author" placeholder="请输入作者" clearable />
      </el-form-item>
      <el-form-item>
        <el-input v-model="bookId" placeholder="请输入图书编号" clearable />
      </el-form-item>
      <!-- <el-form-item label="发布状态：">
                <el-select placeholder="请选择" v-model="state">
                    <el-option label="已发布" value="已发布"></el-option>
                    <el-option label="草稿" value="草稿"></el-option>
                </el-select>
            </el-form-item> -->
          <br>
      <el-form-item>
        <el-button type="primary" @click="bookList">搜索</el-button>
        <el-button
          @click="
            categoryId = '';
            bookname = '';
            author = '';
            bookId = '';
            bookList();
          "
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 文章列表 -->
    <el-table :data="book" style="width: 100%">
      <el-table-column label="序号" type="index"> </el-table-column>
      <el-table-column label="书名" prop="bookname"></el-table-column>
      <el-table-column label="分类" prop="categoryName"></el-table-column>
      <el-table-column label="作者" prop="author"> </el-table-column>
      <el-table-column label="数量" prop="num"></el-table-column>
      <el-table-column label="地点" prop="address"></el-table-column>
      <el-table-column label="编号" prop="idNumber"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button
            :icon="Edit"
            circle
            plain
            type="primary"
            @click="showDrawer(row)"
          ></el-button>
          <el-button
            :icon="Delete"
            circle
            plain
            type="danger"
            @click="deleteBook(row)"
          ></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next"
      background
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />

    <!-- 抽屉 -->
    <el-drawer
      v-model="visibleDrawer"
      :title="title"
      direction="rtl"
      size="30%"
    >
      <!-- 添加文章表单 -->
      <el-form :model="bookModel" label-width="100px" :rules="rules">
        <el-form-item label="书名" prop="bookname">
          <el-input
            v-model="bookModel.bookname"
            placeholder="请输入书名"
          ></el-input>
        </el-form-item>
        <el-form-item label="图书分类">
          <el-select placeholder="请选择" v-model="bookModel.type">
            <el-option
              v-for="c in categorys"
              :key="c.id"
              :label="c.name"
              :value="c.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="作者">
          <el-input
            v-model="bookModel.author"
            placeholder="请输入作者"
          ></el-input>
          <!-- <el-upload class="avatar-uploader" :auto-upload="false" :show-file-list="false">
                        <img v-if="articleModel.coverImg" :src="articleModel.coverImg" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload> -->
        </el-form-item>
        <el-form-item label="数量">
          <el-input-number v-model="bookModel.num" :min="1" />
          <!-- <div class="editor">富文本编辑器</div> -->
        </el-form-item>

        <el-form-item label="地点">
          <el-input
            v-model="bookModel.address"
            placeholder="请输入图书存放位置"
          ></el-input>
        </el-form-item>
        <el-form-item label="编号" prop="idNumber">
          <el-input
            v-model="bookModel.idNumber"
            placeholder="请输入图书编号"
            :disabled="title == '修改图书' ? true : false"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="title == '添加图书' ? addBook() : updateBook()"
            >确认</el-button
          >
          <el-button @click="visibleDrawer = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </el-card>
</template>
<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

/* 抽屉样式 */
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>